import { injectComponents } from '@alilc/lowcode-plugin-inject'
import { AssetLoader, buildComponents } from '@alilc/lowcode-utils'
import { useEffect, useState } from 'react'

import { getPackagesById, getProjectSchemaById } from './tools'

export default () => {
  const [loading, setLoading] = useState(true)
  const [schemaLocal, setSchemaLocal] =
    useState<
      ReturnType<typeof getProjectSchemaById>['componentsTree'][number]
    >()
  const [componentsLocal, setComponentsLocal] = useState<any>()

  const init = async () => {
    try {
      setLoading(true)
      // 渲染前置处理，初始化项目 schema 和资产包为渲染模块所需的 schema prop 和 components prop
      const projectPackages = getPackagesById()
      const projectSchema = getProjectSchemaById()
      const { componentsMap: componentsMapArray, componentsTree } =
        projectSchema
      const componentsMap: any = {}
      componentsMapArray.forEach((component: any) => {
        componentsMap[component.componentName] = component
      })
      const schema = componentsTree[0]
      setSchemaLocal(schema)

      const libraryMap: Record<string, any> = {}
      const libraryAsset: any[] = []
      projectPackages.forEach(
        ({ package: packageName, library, urls, renderUrls }) => {
          libraryMap[packageName] = library
          if (renderUrls) {
            libraryAsset.push(renderUrls)
          } else if (urls) {
            libraryAsset.push(urls)
          }
        },
      )

      // const vendors = [assetBundle(libraryAsset, AssetLevel.Library)];

      const assetLoader = new AssetLoader()
      await assetLoader.load(libraryAsset)
      console.log('libraryMap', libraryMap)
      console.log('componentsMap', componentsMap)
      const components = await injectComponents(
        buildComponents(libraryMap, componentsMap, () => null),
      )

      setSchemaLocal(schema)
      setComponentsLocal(components)
    } catch (error) {
      console.log('error')
    } finally {
      setLoading(false)
    }
  }
  useEffect(() => {
    init()
  }, [])

  return { schema: schemaLocal, components: componentsLocal, loading }
}
